<template>
  <!-- 搜索工作栏 -->
  <ContentWrap>
    <el-form class="-mb-15px" :model="queryParams" ref="queryFormRef" :inline="true">
      <el-form-item label="机构名称" prop="name">
        <ns-input
          v-model="queryParams.name"
          placeholder="请输入机构名称"
          clearable
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="所属区域" prop="cityId">
        <el-tree-select
          class="!w-240px"
          v-model="queryParams.cityId"
          :data="areaTree"
          :props="{
            children: 'children',
            label: 'name',
            value: 'id'
          }"
          placeholder="请选择所属区域"
          :default-expanded-keys="expandedKeys"
          value-key="id"
          node-key="id"
        />
      </el-form-item>
      <el-form-item label="机构状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择机构状态"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-row>
        <el-col :span="24" class="text-right">
          <el-form-item>
            <el-button @click="handleQuery">搜索</el-button>
            <el-button @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <div style="width: 100%" ref="tableWrapRef">
      <el-form-item>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['system:dept:create']"
        >
          新增
        </el-button>
        <el-button type="primary" plain @click="batchCrate" v-hasPermi="['system:dept:batchCrate']">
          批量新增
        </el-button>
        <el-button class="ml-4" @click="handleExport" :loading="exportLoading"> 导出 </el-button>
        <el-button @click="handleImport"> 导入</el-button>
      </el-form-item>
      <div style="width: 100%; height: calc(100vh - 480px)">
        <el-auto-resizer>
          <template #default="{ height, width }">
            <el-table-v2
              v-model:expanded-row-keys="expandedRowKeys"
              :columns="columns"
              :data="list"
              :width="width"
              expand-column-key="name"
              row-key="id"
              :height="height"
              fixed
              @row-expand="onRowExpanded"
              @expanded-rows-change="onExpandedRowsChange"
              layout="fixed"
            />
          </template>
        </el-auto-resizer>
      </div>
    </div>
  </ContentWrap>
  <el-dialog
    v-model="uploadResultDia"
    title="导入结果"
    width="70%"
    v-if="uploadResultDia"
    align-center
  >
    <h2 class="mb-25px">上传成功数量：{{ successQuantity }}</h2>
    <h2 class="my-25px">上传失败数量：{{ failTable.data.length }}</h2>
    <AsyncTable
      v-bind="failTable"
      ref="failTableRef"
      max-height="340px"
      :showSift="false"
      :isPage="false"
    />
    <template #footer>
      <el-button type="primary" @click="uploadResultDia = false">确认</el-button>
    </template>
  </el-dialog>
  <!-- 表单弹窗：添加/修改 -->
  <DeptForm ref="formRef" @success="getList" />
  <MoveForm ref="moveFormRef" @success="getList" />
  <ImportForm ref="importFormRef" @success="getList" />
  <BatchCreate :dialogVisible="dialogVisible" @close="close" v-if="dialogVisible" />
</template>
<script lang="tsx" setup>
import ImportForm from './components/ImportForm.vue'
import MoveForm from './components/MoveForm.vue'
import BatchCreate from './components/BatchCreate.vue'
import download from '@/utils/download'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import * as DeptApi from '@/api/system/dept'
import DeptForm from './DeptForm.vue'
import * as UserApi from '@/api/system/user'
import * as AreaApi from '@/api/system/area'
import { checkPermi } from '@/utils/permission'

import type { ExpandedRowsChangeHandler } from 'element-plus'

defineOptions({ name: 'SystemDept' })

const dialogVisible = ref(false)
const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const tableWrapRef = ref()
// el-table-v2
const formatData = (v) => {
  return v < 10 ? '0' + v : v
}
const uploadResultDia = ref(false)

const columns = [
  {
    key: 'name',
    dataKey: 'name',
    title: '名称',
    width: 300
  },
  {
    key: 'sort',
    dataKey: 'sort',
    title: '排序',
    width: 120,
    align: 'center'
  },
  {
    key: 'status',
    dataKey: 'status',
    title: '状态',
    width: 120,
    align: 'center',
    cellRenderer: ({ rowData }) => (
      <>
        <dict-tag type={DICT_TYPE.COMMON_STATUS} value={rowData.status} />
      </>
    )
  },
  {
    key: 'createTime',
    dataKey: 'createTime',
    title: '创建时间',
    width: 240,
    align: 'center',
    cellRenderer: ({ rowData }) => (
      <>{`${rowData.createTime.date.year}-${formatData(rowData.createTime.date.month)}-${formatData(rowData.createTime.date.day)} ${formatData(rowData.createTime.time.hour)}:${formatData(rowData.createTime.time.minute)}:${formatData(rowData.createTime.time.second)}`}</>
    )
  },
  {
    key: 'operations',
    title: '操作',
    cellRenderer: ({ rowData }) => (
      <>
        {checkPermi(['system:dept:transfer']) && rowData.children.length == 0 && (
          <el-button link type="primary" onClick={() => openMove(rowData)}>
            迁移
          </el-button>
        )}
        {checkPermi(['system:dept:update']) && (
          <el-button link type="primary" onClick={() => openForm('update', rowData.id)}>
            修改
          </el-button>
        )}
        {checkPermi(['system:dept:delete']) && (
          <el-button link type="danger" onClick={() => handleDelete(rowData.id)}>
            删除
          </el-button>
        )}
      </>
    ),
    width: 250,
    fixed: 'right',
    align: 'center'
  }
]

const expandedRowKeys = ref<string[]>([])

const batchCrate = () => {
  dialogVisible.value = true
}

const onRowExpanded = ({ expanded }) => {
  console.log('Expanded:', expanded)
}

const onExpandedRowsChange = (expandedKeys: Parameters<ExpandedRowsChangeHandler>[0]) => {
  console.log(expandedKeys)
}

const tableWidth = ref(1200)

//封装getTableWitdh()方法
const getTableWitdh = () => {
  tableWidth.value = tableWrapRef.value.offsetWidth
}
// 监听屏幕宽度变化
window.addEventListener('resize', getTableWitdh)

const close = (isAdd) => {
  dialogVisible.value = false
  isAdd && handleQuery()
}
const list = ref([]) // 列表的数据
const queryParams = reactive({
  title: '',
  name: undefined,
  status: undefined,
  cityId: undefined,
  page: 1,
  pageSize: 100
})
const queryFormRef = ref() // 搜索的表单
const userList = ref<UserApi.UserVO[]>([]) // 用户列表
const areaTree = ref() //区域树形结构
const expandedKeys = ref<number[]>([])
const successQuantity = ref(0)

const failTable = ref({
  columns: [
    { type: 'index', label: '序号', width: '60px' },
    {
      label: '失败原因',
      render: ({ row }) => {
        return <div>{row}</div>
      },
      'min-width': '340px',
      'show-overflow-tooltip': true
    }
  ],
  data: []
})
/** 查询机构列表 */
const getList = async (info, isDialog) => {
  if (isDialog) {
    successQuantity.value = info?.createDeptNames?.length
    failTable.value.data = info?.failureDeptNames
    uploadResultDia.value = true
  }
  const data = await DeptApi.getDeptPage(queryParams)
  console.log('data', data)
  list.value = data
}

/** 搜索按钮操作 */
const handleQuery = () => {
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryParams.page = 1
  queryFormRef.value.resetFields()
  handleQuery()
}

const importFormRef = ref()
const handleImport = () => {
  importFormRef.value.open()
}

// 导出
const exportLoading = ref(false)
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await DeptApi.deptExportExcel({ ...queryParams })
    download.excel(data, '机构.xlsx')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    const data = await DeptApi.deleteDept(id)
    console.log('data', data)
    if (data.code === 999999999) {
      message.warning(data.message)
    } else {
      message.success(t('common.delSuccess'))
    }
    // 刷新列表
    await getList()
  } catch {}
}

const moveFormRef = ref()
const openMove = (row) => {
  moveFormRef.value.open(row.id, row.name)
}

/** 获取省市树 */
async function getAreaTree() {
  const res = await AreaApi.getAreaTree2()
  areaTree.value = res
}

/** 初始化 **/
onMounted(async () => {
  getTableWitdh()
  await getList()
  // 获取用户列表
  userList.value = await UserApi.getSimpleUserList()
  getAreaTree()
})
</script>
